package cn.hairui.blog.controller;

import cn.hairui.blog.configure.WebLog;
import cn.hairui.blog.constant.PubConstant;
import cn.hairui.blog.entity.Album;
import cn.hairui.blog.entity.Myinfo;
import cn.hairui.blog.entity.User;
import cn.hairui.blog.service.AlbumService;
import cn.hairui.blog.service.MyinfoService;
import cn.hairui.blog.util.DateUtil;
import cn.hairui.blog.util.BlogUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 相册表 前端控制器
 * </p>
 *
 * @author laoganbu
 * @since 2020-04-15
 */
@Controller

public class AlbumController {

    @Autowired
    private AlbumService albumService;
    @Autowired
    private MyinfoService myinfoService;

    @Value("${upload_path}")
    private String uploadPath;

    @Value("${virtual_upload_path}")
    private String virtualUploadPath;

    //// ==========================前台==============================///////
    @RequestMapping(value = "/album")
    @WebLog(description = "查看相册")
    public String album(HttpServletRequest request, Model model) {
        // 我的信息
        Myinfo myinfo = myinfoService.getById(PubConstant.MY_INFO_ID);
        model.addAttribute("myinfo", myinfo);

        User user = (User) request.getSession().getAttribute(PubConstant.GLOBAL_SESSION_NAME);
        if (user != null && PubConstant.USER_TYPE_SUPER_ADMIN.equals(user.getType())) {

            int pageSize = 6;// 默认每页显示6条记录
            Integer pageNum = null;
            String pageNumStr = request.getParameter("pageIndex");
            if (pageNumStr != null) {
                pageNum = Integer.parseInt(pageNumStr);
            }
            if (pageNum == null) {
                pageNum = 1;
            }

            PageHelper.startPage(pageNum, pageSize);
            List<Album> albumsList = null;
            QueryWrapper<Album> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("SHOW_FLAG", PubConstant.YES_NO_Y);
            albumsList = albumService.list(queryWrapper);

            PageInfo<Album> pageInfo = new PageInfo<Album>(albumsList);
            Iterator albumsIterator = albumsList.iterator();
            List<Map> albums = new ArrayList<>();
            while (albumsIterator.hasNext()) {
                Map map = new HashMap();
                Album album = (Album) albumsIterator.next();

                int id = album.getId();
                String name = album.getName();
                String desc = album.getIntroduction();
                int num = albumService.getImagesCount(id);

                map.put("id", id);
                map.put("name", name);
                map.put("cover", album.getShowImg());
                map.put("time", album.getCreateTime().substring(0, 10));
                map.put("num", num);
                map.put("desc", desc);
                map.put("location", album.getLocation());
                albums.add(map);
            }
            model.addAttribute("albums", albums);
            model.addAttribute("pageInfo", pageInfo);
            model.addAttribute("pageIndex", pageNum);
            model.addAttribute("pageSize", pageSize);

        } else {
            return "redirect:error/403";
        }
        return "album";
    }

    //// ==========================后台==============================///////

    // 列表页面
    @RequestMapping(value = "/manage/album/list")
    public String list() {
        return "page/album/list";
    }

    // 新增页面
    @RequestMapping(value = "/manage/album/add")
    public String add() {
        return "page/album/add";
    }

    // 修改页面
    @RequestMapping(value = "/manage/album/update")
    public String update(HttpServletRequest request, Model model) {
        int id = Integer.parseInt(request.getParameter("id"));
        Album album = albumService.getById(id);
        model.addAttribute("album", album);
        return "page/album/update";
    }

    // 列表数据
    @RequestMapping(value = "/manage/album/data")
    @ResponseBody
    public String list(HttpServletRequest request) {
        Map map = new HashMap<Object, Object>();
        int pageSize = 5;// 默认每页显示5条记录
        int pageNum = 1;
        try {
            pageNum = Integer.parseInt(request.getParameter("page"));
            pageSize = Integer.parseInt(request.getParameter("limit"));
        } catch (Exception e) {
        }

        PageHelper.startPage(pageNum, pageSize);
        List<Map> albumList = albumService.listMgr();

        PageInfo<Map> pageInfo = new PageInfo<Map>(albumList);
        map.put("data", albumList);
        map.put("code", 0);
        map.put("count", pageInfo.getTotal());
        return JSONUtils.toJSONString(map);
    }

    // 新增数据
    @RequestMapping(value = "/manage/album/addData")
    @ResponseBody
    @Transactional
    public String addData(HttpServletRequest request, Album album) {
        Map map = new HashMap<Object, Object>();
        // 处理分类置顶

        if (PubConstant.ON.equals(album.getShowFlag())) {
            album.setShowFlag(PubConstant.YES_NO_Y);
        } else {
            album.setShowFlag(PubConstant.YES_NO_N);
        }
        // 设置默认时间 添加人
        User userinfo = (User) request.getSession().getAttribute(PubConstant.GLOBAL_SESSION_NAME);
        album.setCreator(userinfo.getAccount());
        album.setCreateTime(DateUtil.getCurrentTime());

        String fileName = "";
        File targetPath = new File(uploadPath + PubConstant.ALBUM_DIR + PubConstant.COVERS_DIR);
        if (!targetPath.exists()) {
            targetPath.mkdirs();
        }

        // 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        // 检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            // 将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                // 一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if (file != null) {
                    fileName = file.getOriginalFilename();
                    String suffixName = fileName.substring(fileName.lastIndexOf("."));
                    // 重新生成文件名
                    fileName = BlogUtil.getUUIDUpperCase() + suffixName;
                    String path = uploadPath + PubConstant.ALBUM_DIR + PubConstant.COVERS_DIR + fileName;
                    // 上传
                    try {
                        file.transferTo(new File(path));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        album.setShowImg(fileName);
        albumService.saveOrUpdate(album);
        map.put(PubConstant.flag, PubConstant.success);
        return JSONUtils.toJSONString(map);
    }

    // 删除操作
    @RequestMapping(value = "/manage/album/delete", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public String delete(@Param(value = "id") int id, HttpServletRequest request) {
        Map map = new HashMap();
        // 判断权限
        User user = (User) request.getSession().getAttribute(PubConstant.GLOBAL_SESSION_NAME);
        if (user != null && PubConstant.USER_TYPE_SUPER_ADMIN.equals(user.getType())) {
            Album album = albumService.getById(id);
            albumService.removeById(id);
            try {
                // 删除文件
                String fileName = album.getShowImg();
                File file = new File(uploadPath + PubConstant.ALBUM_DIR + PubConstant.COVERS_DIR + fileName);
                if (file.exists() && fileName != null && !"".equals(fileName)) {
                    file.delete();
                }
            } catch (Exception e) {
            }
            map.put(PubConstant.flag, PubConstant.success);
        }
        return JSONUtils.toJSONString(map);
    }

    // 更新数据
    @RequestMapping(value = "/manage/album/updateData")
    @ResponseBody
    public String updateData(HttpServletRequest request, Album album) {
        Map map = new HashMap<Object, Object>();
        if (album != null && album.getShowFlag() != null && PubConstant.ON.equals(album.getShowFlag())) {
            album.setShowFlag(PubConstant.YES_NO_Y);
        } else {
            album.setShowFlag(PubConstant.YES_NO_N);
        }
        albumService.saveOrUpdate(album);
        map.put(PubConstant.flag, PubConstant.success);
        return JSONUtils.toJSONString(map);
    }

    // 展示标志修改
    @RequestMapping(value = "/manage/album/show")
    @ResponseBody
    public String show(HttpServletRequest request) {
        Map map = new HashMap<Object, Object>();
        int id = Integer.parseInt(request.getParameter("id"));

        Album album = albumService.getById(id);
        if (PubConstant.YES_NO_Y.equals(album.getShowFlag())) {
            // 取消置顶
            album.setShowFlag(PubConstant.YES_NO_N);
        } else {
            // 置顶
            album.setShowFlag(PubConstant.YES_NO_Y);
        }
        albumService.saveOrUpdate(album);
        map.put(PubConstant.flag, PubConstant.success);
        return JSONUtils.toJSONString(map);
    }
}
